﻿using MyAbpFrame.Application.Contracts.User;
using MyAbpFrame.Application.LocalHandlers.HandlerEvents;
using MyAbpFrame.Application.User.Dto;
using MyAbpFrame.Domain.UserInfo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.EventBus.Local;

namespace MyAbpFrame.Application.User
{
    public class UserAppService : ApplicationService, IUserAppService
    {
        /// <summary>
        /// 本地事件总线
        /// </summary>
        private readonly ILocalEventBus _localEventBus;
        private IRepository<Users> _userRepository;   //IRepository需要添加abp.AutoFac不然会报错（MVC层）  还需要在AppModule注入，以及Program中加入UseAutofac()
        public UserAppService(IRepository<Users> userRepository, ILocalEventBus localEventBus)
        {
            _userRepository = userRepository;
            _localEventBus = localEventBus;
        }
        public async Task<UserDto> Get(string userNo, string password)
        {
            var user = await _userRepository.GetAsync(m => m.UserNo == userNo && m.Password == password);
            var dto = ObjectMapper.Map<Users, UserDto>(user);
            await ChangeStockCountAsync(new Guid(), 50);
            return dto;
        }
        /// <summary>
        /// 发布事件
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="newCount"></param>
        /// <returns></returns>
        public virtual async Task ChangeStockCountAsync(Guid productId, int newCount)
        {
            //TODO: IMPLEMENT YOUR LOGIC...

            //PUBLISH THE EVENT
            await _localEventBus.PublishAsync(
                new StockCountChangedEvent
                {
                    ProductId = productId,
                    NewCount = newCount
                }
            );
        }
    }
}
